
//Lo guarda aqui:    /Users/Alvaro/GlassFish_Server/glassfish/domains/domain1

package ChangeUserInfo;

import classes.AdminDB;
import classes.user;
import java.io.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.*;
 
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Cookie;


import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.output.*;

public class changePhotoUser extends HttpServlet {
   
   private boolean isMultipart;
   private String filePath;
   private int maxFileSize = 500 * 1024;
   private int maxMemSize = 4 * 1024;
   private File file ;

   public void init( ){
      // Get the file location where it would be stored.
      filePath = "/Users/Alvaro/Desktop/ShopOnline/ShopOnline/web/images/userphotos/";//getServletContext().getInitParameter("file-upload"); 
   }
   public void doPost(HttpServletRequest request,HttpServletResponse response)
              throws ServletException, java.io.IOException {
      // Check that we have a file upload request
      isMultipart = ServletFileUpload.isMultipartContent(request);
      response.setContentType("text/html");
      java.io.PrintWriter out = response.getWriter( );
      
      
      
      
        //Recuperamos el valor de la cookie. 
        String cookieName = "email";
        Cookie cookies [] = request.getCookies ();
        Cookie email = null;
        if (cookies != null)
        {
            for (int i = 0; i < cookies.length; i++) 
            {
                if (cookies [i].getName().equals (cookieName))
                {
                    email = cookies[i];
                    break;
                }
            }
        }
        System.out.println("Email: "+email.getValue());

      
      
      
      if( !isMultipart ){
//         out.println("<html>");
//         out.println("<head>");
//         out.println("<title>Servlet upload</title>");  
//         out.println("</head>");
//         out.println("<body>");
//         out.println("<p>No file uploaded</p>"); 
//         out.println("</body>");
//         out.println("</html>");
         return;
      }
      DiskFileItemFactory factory = new DiskFileItemFactory();
      // maximum size that will be stored in memory
      factory.setSizeThreshold(maxMemSize);
      // Location to save data that is larger than maxMemSize.
      factory.setRepository(new File("/Users/Alvaro/Desktop/ShopOnline/ShopOnline/web/Admin"));

      // Create a new file upload handler
      ServletFileUpload upload = new ServletFileUpload(factory);
      // maximum file size to be uploaded.
      upload.setSizeMax( maxFileSize );

      try{ 
      // Parse the request to get file items.
      List fileItems = upload.parseRequest(request);
	
      // Process the uploaded file items
      Iterator i = fileItems.iterator();

//      out.println("<html>");
//      out.println("<head>");
//      out.println("<title>Servlet upload</title>");  
//      out.println("</head>");
//      out.println("<body>");
      while ( i.hasNext () ) 
      {
         FileItem fi = (FileItem)i.next();
         if ( !fi.isFormField () )	
         {
            // Get the uploaded file parameters
            String fieldName = fi.getFieldName();
            String fileName = fi.getName();
            String contentType = fi.getContentType();
            boolean isInMemory = fi.isInMemory();
            long sizeInBytes = fi.getSize();
            // Write the file
            if( fileName.lastIndexOf("\\") >= 0 ){
               file = new File( filePath + 
               fileName.substring( fileName.lastIndexOf("\\"))) ;
            }else{
               file = new File( filePath + 
               fileName.substring(fileName.lastIndexOf("\\")+1)) ;
            }
            fi.write( file ) ;

            user u = new user();
            AdminDB conn = new AdminDB();
            //Cambiamos la foto del usuario y le ponemos el nombre de la propia foto que se sube al servidor
            u.changePhoto(conn.getConnection(), fileName, email.getValue());
            //Redireccion
            response.sendRedirect("options.jsp" );           

         }
      }

   }catch(Exception ex) {
       System.out.println(ex);
   }
   }
   public void doGet(HttpServletRequest request, 
                       HttpServletResponse response)
        throws ServletException, java.io.IOException {
        
        throw new ServletException("GET method used with " +
                getClass( ).getName( )+": POST method required.");
   } 
}